#include "platform/sdl_mixer/audio_api.hpp"

namespace Xen {

SDLMixerAPI::SDLMixerAPI() {
    Mix_Init(MIX_INIT_FLAC|MIX_INIT_MID|MIX_INIT_MOD|MIX_INIT_OGG|MIX_INIT_MP3|MIX_INIT_OPUS);
    if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024) == -1) {
        XEN_CORE_ASSERT(false, "SDL2 Mixer OpenAudio Failed: " + std::string(Mix_GetError()));
    }
}

SDLMixerAPI::~SDLMixerAPI() {
    Mix_CloseAudio();
    Mix_Quit();
}

void SDLMixerAPI::Play(const Ref<AudioSource> &source) {
    SDLMixerBuffer* buffer = dynamic_cast<SDLMixerBuffer*>(source->GetBindedBuffer().get());
    int channel = buffer->GetChannels();
    Mix_Volume(channel, MIX_MAX_VOLUME);
    if (source->IsLoop()) {
        Mix_PlayChannel(channel, buffer->GetChunk(), -1);
    } else {
        Mix_PlayChannel(channel, buffer->GetChunk(), 0);
    }
}

void SDLMixerAPI::Pause(const Ref<AudioSource> &source) {
    SDLMixerBuffer* buffer = dynamic_cast<SDLMixerBuffer*>(source->GetBindedBuffer().get());
    int channel = buffer->GetChannels();
    Mix_Pause(channel);
}

void SDLMixerAPI::Stop(const Ref<AudioSource> &source) {
    SDLMixerBuffer* buffer = dynamic_cast<SDLMixerBuffer*>(source->GetBindedBuffer().get());
    int channel = buffer->GetChannels();
    Mix_HaltChannel(channel);
}

void SDLMixerAPI::Rewind(const Ref<AudioSource> &source) {
    SDLMixerBuffer* buffer = dynamic_cast<SDLMixerBuffer*>(source->GetBindedBuffer().get());
    int channel = buffer->GetChannels();
    if (source->IsLoop()) {
        Mix_PlayChannel(channel, buffer->GetChunk(), -1);
    } else {
        Mix_PlayChannel(channel, buffer->GetChunk(), 0);
    }
}

}

